﻿using AutoMapper;
using B.S.BasicData.Api.Write.Applications.Command;
using B.S.BasicData.Domains;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructures;
using MediatR;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using System.ComponentModel;

namespace B.S.BasicData.Api.Write.Applications.CommandHandler
{
    public class AddRoleUserCommandHandler : IRequestHandler<AddRoleUserCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<UserInfos> userRepository;
        private readonly IBaseRepository<RoleUser> roleuserRepository;
        private readonly IMapper mapper;
        private readonly ILogger<AddRoleUserCommandHandler> logger;

        public AddRoleUserCommandHandler(IBaseRepository<UserInfos> userRepository, IBaseRepository<RoleUser> roleuserRepository, IMapper mapper, ILogger<AddRoleUserCommandHandler> logger)
        {
            this.userRepository = userRepository;
            this.roleuserRepository = roleuserRepository;
            this.mapper = mapper;
            this.logger = logger;
        }

        public async Task<ApiResult<int>> Handle(AddRoleUserCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result=new ApiResult<int>();
            result.Code = ApiEnum.Success;
            result.Message = "角色用户添加成功";
            using (var tran=userRepository.DB.Database.BeginTransaction())
            {
                try
                {
                    //用户
                    logger.LogInformation("角色用户添加成功");
                    UserInfos userInfos = mapper.Map<UserInfos>(request);
                    await userRepository.Add(userInfos);
                    //用户角色
                    var list=new List<RoleUser>();
                    foreach(var item in request.RoleIds)
                    {
                        list.Add(new RoleUser
                        {
                            UserId= userInfos.UserId,
                            RoleId=item

                        });
                            
                    }
                    await roleuserRepository.AddRange(list);

                    tran.Commit();
                }
                catch(Exception ex)
                {
                    logger.LogInformation("角色用户添加失败"+ex.Message);
                    result.Code = ApiEnum.Fail;
                    result.Message = "角色用户失败";
                    tran.Rollback();
                }

            }
            return await Task.FromResult(result);
        }
    }
}
